package com.yjt.common.utils;

import com.yjt.common.entity.oauth.CommonUser;
import com.yjt.common.vo.UserDetailVO;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * @author 曾智平
 * @ClassName: SecurityUtils
 * @Description: 获取当前用户信息类
 * @date 2021/9/27 10:44
 */
public class SecurityUtils {
    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        SecurityContext securityContext =  SecurityContextHolder.getContext();

        return SecurityContextHolder.getContext().getAuthentication();
    }

    public static UserDetails getUserDetails() {
        Authentication authentication = getAuthentication();
        if (authentication == null || authentication.getPrincipal() == null) {
            return null;
        }
        return (UserDetails) authentication.getPrincipal();
    }

    /**
     * 获取当前用户id
     * @return
     */
    public static String getUserId() {
        Authentication authentication = getAuthentication();
        if (authentication == null) {
            return null;
        }
        return authentication.getName();
    }
    /**
     * 获取当前用户信息
     * @return
     */
    public static CommonUser getCurrentUser(){
        return  ((UserDetailVO) getUserDetails()).getCommonUser();
    }

}
